#include "music.h"

#include <QUuid>
#include <QMediaPlayer>
#include <QCoreApplication>
#include <QSqlQuery>
#include <QSqlError>
#include <QBuffer>
#include <QDebug>

Music::Music()
    : isLike(false)
    , isHistory(false)
{

}

Music::Music(const QUrl &url)
    : isLike(false)
    , isHistory(false)
    , musicUrl(url)
{
    // 生成唯一的id
    musicId = QUuid::createUuid().toString();

    // 读取url对应的歌曲文件的信息，解析出元数据
    parseMediaMetaMusic();
}

void Music::setMusicName(const QString &musicName)
{
    this->musicName = musicName;
}

void Music::setMusicSinger(const QString &musicSinger)
{
    this->musicSinger = musicSinger;
}

void Music::setMusicAlbum(const QString &musicAlbum)
{
    this->musicAlbum = musicAlbum;
}

void Music::setDuration(qint64 duration)
{
    this->duration = duration;
}

void Music::setCoverImage(const QByteArray &imageData)
{
    coverImage.loadFromData(imageData);
}

void Music::setIsLike(bool isLike)
{
    this->isLike = isLike;
}

void Music::setIsHistory(bool isHistory)
{
    this->isHistory = isHistory;
}

void Music::setMusicUrl(const QUrl &musicUrl)
{
    this->musicUrl = musicUrl;
}

void Music::setMusicId(const QString &musicId)
{
    this->musicId = musicId;
}

QString Music::getMusicName() const
{
    return musicName;
}

QString Music::getMusicSinger() const
{
    return musicSinger;
}

QString Music::getMusicAlbum() const
{
    return musicAlbum;
}

qint64 Music::getDuration() const
{
    return duration;
}

QPixmap Music::getCoverImage() const
{
    return coverImage;
}

bool Music::getIsLike() const
{
    return isLike;
}

bool Music::getIsHistory() const
{
    return isHistory;
}

QUrl Music::getMusicUrl() const
{
    return musicUrl;
}

QString Music::getMusicId() const
{
    return musicId;
}

QString Music::getLrcFilePath() const
{
    QString lrcPath = musicUrl.toLocalFile();
    lrcPath.replace(".mp3", ".lrc");
    lrcPath.replace(".flac", ".lrc");
    lrcPath.replace(".mpga", ".lrc");
    return lrcPath;
}

void Music::insertMusicToDB()
{
    // 1. 检测music是否在数据库中存在
    QSqlQuery query;
    query.prepare("SELECT EXISTS (SELECT 1 FROM MusicInfo WHERE musicId = ?);");
    query.addBindValue(musicId);
    if (!query.exec())
    {
        qDebug() << "查询失败：" << query.lastError().text();
        return;
    }
    if (query.next())
    {
        bool isExists = query.value(0).toBool();  // 获取查询结果
        if (isExists)
        {
            // 2. 如果存在，不需要再插入，只需将isLike和isHistory属性进行更新即可
            query.prepare("UPDATE MusicInfo SET isLike = ?, isHistory = ? WHERE musicId = ?");
            query.addBindValue(isLike ? 1 : 0);
            query.addBindValue(isHistory ? 1 : 0);
            query.addBindValue(musicId);
            if (!query.exec())
            {
                qDebug() << "更新失败：" << query.lastError().text();
                return;
            }
            qDebug() << "更新music信息：" << musicName;
        }
        else
        {
            // 3. 如果不存在，直接将Music的属性信息插入数据库
            query.prepare("INSERT INTO MusicInfo (musicId, musicName, musicSinger, albumName, musicUrl, duration, isLike, isHistory, coverImage) VALUES (?,?,?,?,?,?,?,?,?)");
            query.addBindValue(musicId);
            query.addBindValue(musicName);
            query.addBindValue(musicSinger);
            query.addBindValue(musicAlbum);
            query.addBindValue(musicUrl.toLocalFile());
            query.addBindValue(duration);
            query.addBindValue(isLike ? 1 : 0);
            query.addBindValue(isHistory ? 1 : 0);

            // 将图片转换为二进制数据
            QByteArray imageData;
            QBuffer buffer(&imageData);
            buffer.open(QIODevice::WriteOnly);
            coverImage.save(&buffer, "JPG");  // 保存为JPEG格式
            buffer.close();
            // 将二进制数据保存到数据库
            query.addBindValue(imageData);

            if (!query.exec())
            {
                qDebug() << "插入失败：" << query.lastError().text();
                return;
            }
            qDebug() << "插入music信息：" << musicName;
        }
    }
}

void Music::parseMediaMetaMusic()
{
    // 1. 创建媒体播放对象
    QMediaPlayer player;

    // 2. 设置媒体源，通过setMedia方法解析元数据
    player.setMedia(musicUrl);

    // 3. setMedia会立即返回，不会等待媒体加载完成。我们要获取元数据，必须保证媒体已经添加完毕
    // 可以通过isMetaDataAvailable()检测数据是否有效
    while (!player.isMetaDataAvailable())
    {
        QCoreApplication::processEvents();
    }

    // 4. 走到这里，加载已经完成，可以获取有效的元数据了
    musicName = player.metaData("Title").toString();
    musicSinger = player.metaData("Author").toString();
    musicAlbum = player.metaData("AlbumTitle").toString();
    duration = player.metaData("Duration").toLongLong();
    QVariant image = player.metaData("ThumbnailImage");
    if (image.isValid())
    {
        coverImage = QPixmap::fromImage(image.value<QImage>());
    }
    else
    {
        // 如果该歌曲文件没有缩略图，就用默认的封面图
        coverImage = QPixmap(":/images/default_album_image.png");
    }
//    qDebug() << musicName << ": " << duration << ", " << player.duration();

    // 5. 处理元数据为空的情况
    QString fileName = musicUrl.fileName();
//    qDebug() << fileName;
    int index = fileName.indexOf('-');
    // 歌名为空
    if (musicName.isEmpty())
    {
        if (index != -1)
        {
            // "歌手 - 歌名.mp3"
            musicName = fileName.mid(index + 1, fileName.indexOf('.') - index - 1).trimmed();
        }
        else
        {
            // "歌名.mp3"
            musicName = fileName.mid(0, fileName.indexOf('.')).trimmed();
        }
    }
    // 作者为空
    if (musicSinger.isEmpty())
    {
        if (index != -1)
        {
            musicSinger = fileName.mid(0, index).trimmed();
        }
        else
        {
            musicSinger = "未知歌手";
        }
    }
    // 专辑为空
    if (musicAlbum.isEmpty())
    {
        musicAlbum = "未知专辑";
    }

//    qDebug() << musicUrl;
//    qDebug() << musicName << ", " << musicSinger << ", " << musicAlbum << ", " << duration;
}
